#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

static WiFiUDP Udp;
const unsigned short udpPort = 11111; // 广播监听端口

// Helper: 获取 MAC 地址字符串
String macToString()
{
    uint8_t mac[6];
    WiFi.macAddress(mac);
    char buf[18];
    sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
            mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
    return String(buf);
}

void listenUDP()
{
    // 直接绑定监听端口即可，不用加入组播
    if (Udp.begin(udpPort)) {
        Serial.printf("Listening for broadcast on port %d\n", udpPort);
    } else {
        Serial.println("UDP begin failed!");
    }

    Serial.printf("Local IP: %s\n", WiFi.localIP().toString().c_str());
    Serial.printf("Subnet Mask: %s\n", WiFi.subnetMask().toString().c_str());
}

void handleUDPPacket()
{
    int len = Udp.parsePacket();
    if (len > 0)
    {
        String msg;
        msg.reserve(len);
        while (Udp.available())
            msg += char(Udp.read());

        Serial.printf("Recv '%s' from %s:%d\n", msg.c_str(), Udp.remoteIP().toString().c_str(), Udp.remotePort());

        if (msg == "DISCOVER")
        {
            String resp = "{\"ip\":\"" + WiFi.localIP().toString() + "\",\"mac\":\"" + macToString() + "\"}";
            Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
            Udp.print(resp);
            Udp.endPacket();
            Serial.println("Responded with device info");
        }
    }
}
